<template>
  	<div class="pay-wrap">
    	<!-- 支付状态 -->
    	<div class="pay-state">
			<div class="pay" v-if="carInfo.payAmount === null">
				<span>待支付</span>
			</div>
			<div class="paySuccess" v-else>
				<p><img src="@/assets/img/icon/zfcg.png" alt=""></p>
				<span>支付成功</span>
			</div>
    	</div>
    
    	<!-- 车辆信息 -->
    	<div class="pay-text" v-if="carInfo.payAmount === null">
			<p class="clearfix">
				<span>号牌号码：</span>
				<span>{{carInfo.carNum}}</span>
			</p>

			<p class="clearfix" v-if="carInfo.payAmount === null">
				<span>检测费用：</span>
				<span>{{carInfo.orderAmount}}元</span>
			</p>
			<p class="clearfix" v-else>
				<span style="margin-right: 10%;">提交时间：</span>
				<em>
				<span>{{seeObject.o}}</span>
				<span>{{seeObject.t}}</span>
				</em>
			</p>

			<p class="clearfix">
				<span style="margin-right: 10%;">检测机构：</span>
				<span>大厂全顺机动车检测有限公司</span>
			</p>
			<p class="clearfix">
				<span>详细地址：</span>
				<span>大厂县潮白河工业园区工业1路68号</span>
			</p>
			<van-cell v-if="carInfo.list.length>0" is-link @click="showPopup" title="贵宾卡" :value="vipCard" />
			<van-popup v-model="show" position="bottom" :style="{ height: '60%'}">
				<div class="con">
					<van-radio-group v-model="carIndex" @change='radioChange'>
						<van-radio :name="item.couponId" shape="square" v-for="item in this.carInfo.list" :key='item.id'>
							<div class="item">
								<div class="card" >
									<h1>{{item.amount}}元</h1>
								</div>
							</div>
						</van-radio>
					</van-radio-group>
					<van-button class="no_vip" type="primary" @click="noVip">不使用贵宾卡</van-button>
				</div>
			</van-popup>
    	</div>

    	<!-- 温馨提示 -->
    	<div class="prompt" v-else>
      		<div >
        		<ul>
					<li>
						<span>点击下方按钮</span>
					</li>
					<li>
						<span>前往单据自助打印机</span>
					</li>
					<li>
						<span>领取单据</span>
					</li>
        		</ul>
      		</div>
    	</div>
    	<!-- button -->
    	<van-button color="#27b5a7" :loading="loading" @click="submitClick">
      		<span v-if="carInfo.payAmount === null" >确认支付</span>
      		<span v-else>打印单据</span>
    	</van-button>
  	</div>
</template>

<script>
/**
 *  支付共2个状态
 * 1.待支付
 * 2.支付成功
 * */
import { getDate } from '@/utils/index'
import { getLocal } from '@/utils/storage'
import wx from 'weixin-js-sdk'
import crypto from 'crypto'
export default {
  	name: 'orderPay',
  	data() {
		return {
			// 支付状态
			payState: false,
			carUser: JSON.parse(getLocal('userInfo')),
			carInfo: {},
			seeObject: {},
			show:false,
			carIndex:null,
			vipCard:null,
			loading:false,
		}
  	},
  	created() {
    	console.log(this.$route.params.carInfo)
    	if (!this.$route.params.carInfo) {
      		this.$router.push('/')
    	} else {
      		this.carInfo = this.$route.params.carInfo
			console.log(this.carInfo, 'this.carInfo')
			if (this.carInfo.list) {
				this.vipCard = `${this.carInfo.list.length}张可用`
			}
    	}
  	},
  	methods: {
		  //打开贵宾卡弹窗
		showPopup(){
			this.show = true
		},
		//选择贵宾卡
		radioChange(name){
			console.log(name)
			this.carInfo.list.forEach(item=>{
				if(item.couponId === name){
					this.vipCard = `-${item.amount}`
				}
			})
			this.show = false
		},
		//不使用贵宾卡
		noVip(){
			this.show = false
			this.carIndex = null
			this.vipCard = `${this.carInfo.list.length}张可用`
		},
    	// 提交操作
    	submitClick() {
      		if (this.carInfo.payAmount === null) {
        		this.wxPayBefore()
      		} else {
        		//this.$router.push('/')
        		this.$router.push({ path: 'printDetails', query: { type:this.carInfo.type,orderType:this.carInfo.orderType,carNum:this.carInfo.carNum,id:this.carInfo.id}})
      		}
    	},
    	// 车检数据查询
    	async queryOrder() {
      		let params = {
        		userId: this.carUser.id,
        		id: ''
      		}
      		let { data } = await this.$api.queryOrder(params)
      		if (data && data.list.length !== 0) {
        		this.orderList = data.list
      		} else {

      		}

      		console.log(data, '------------------- 车检数据查询 ----------------')
    	},
    // 支付接口
    async wxPayBefore() {
		this.loading = true
		let res = await this.$api.wxPayBefore({
			orderId: this.carInfo.id,
			couponId:this.carIndex
		})
		this.loading = false
		if (res) {
			if (res.status == 200) {
				let data = res.data
				if (data) {
					this.wexinPay(data,
						//成功回调函数
						res => {
						this.$toast('支付成功')
						this.carInfo.payAmount = true
						this.seeObject = getDate(new Date().getTime(), 'year')
						console.log(res, '---成功回调函数----')
						
						},
						//取消回调函数
						res => {
							// this.$toast('您取消了支付')
							console.log(res, '----取消回调函数---')
						},
						//失败回调函数
						res => {
							// this.$toast('支付失败')
							console.log(res, '----失败回调函数---')
						}
					)  
				}else{
					this.$toast('支付成功')
					this.carInfo.payAmount = true
					this.seeObject = getDate(new Date().getTime(), 'year')
				}
			}
		}
      	
      	console.log(res, '----------提交支付-----------')
    },

    // 调取微信支付
    wexinPay(data, cb, cancel, fail) {
      //获取后台传入的数据
      let appId = data.appId
      let timestamp = data.timeStamp
      let nonceStr = data.nonceStr
      let signature = data.signature
      let packages = data.package
      let paySign = data.paySign
      let signType = data.signType
      console.log('发起微信支付')
      //下面要发起微信支付了
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: appId, // 必填，公众号的唯一标识
        timestamp: timestamp, // 必填，生成签名的时间戳
        nonceStr: nonceStr, // 必填，生成签名的随机串
        signature: signature, // 必填，签名，见附录1
        jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      })
      wx.ready(function() {
        wx.chooseWXPay({
          timestamp: timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
          nonceStr: nonceStr, // 支付签名随机串，不长于 32 位
          package: packages, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
          signType: signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
          paySign: paySign, // 支付签名
          success: function(res) {
            // 支付成功后的回调函数
            cb(res)
          },
          cancel: function(res) {
            // 取消支付
          },
          fail: function(res) {
            // 支付失败
            //失败回调函数
            errorCb(res)
          }
        })
      })
      wx.error(function(res) {
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        /*alert("config信息验证失败");*/
      })
    },
    // 生成微信签名
    getSign(params, key) {
      const paramsArr = Object.keys(params)
      paramsArr.sort()
      const stringArr = []
      paramsArr.map(key => {
        stringArr.push(key + '=' + params[key])
      })
      // 最后加上 商户Key
      stringArr.push('key=' + key)
      const string = stringArr.join('&')

      return crypto
        .createHash('md5')
        .update(data)
        .digest('hex')
    }
  }
}
</script>

<style lang="less" scoped>
	.pay-wrap {
  		padding-bottom: 0.667rem;
  		.pay-state {
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 0.667rem;
    		.pay {
				display: inline-block;
				background-color: #fd4b05;
				border-radius: 50%;
				min-width: 2rem;
				min-height: 2rem;
				padding: 0.507rem;
				text-align: center;
				box-sizing: content-box;
				line-height: 1;
				white-space: nowrap;
      			&:before {
					content: '';
					display: inline-block;
					vertical-align: middle;
					padding-top: 100%;
					height: 0;
				}
				& > span {
					display: inline-block;
					vertical-align: middle;
					font-size: 0.747rem;
					color: #fff;
				}
    		}
    		.paySuccess{
				img{
					width: 60px;
				}
				& > span {
					display: inline-block;
					vertical-align: middle;
					font-size: 0.4rem;
					font-weight: 600;
					color: #333;
					margin-top: 0.5rem;
				}
    		}
  		}
  		.pay-text {
    		padding: 0.667rem 0 0 0.693rem;
    		p {
				font-size: 0.48rem;
				color: #000;
				margin-bottom: 0.533rem;
      			em {
					float: left;
					width: 100%;
					font-weight: 400;
					span:nth-of-type(1) {
						width: auto;
						margin-right: 8%;
					}
      			}
				span {
					float: left;
					line-height: 0.667rem;
				}
				span:nth-of-type(1) {
					width: 26%;
				}
				span:nth-of-type(2) {
					// width: 70%;
					hyphens: auto;
					word-wrap: break-word; /* old name */
					overflow-wrap: break-word;
					display: inline-block;
				}
			}
			.con{
				padding: 0.4rem 0.3rem;
				margin-bottom: 40px;
				.item{
					width: 90%;
					margin: 0.2rem auto;
					background-color: #efefef;
					background: url(../../assets/img/card.png)center/cover no-repeat;
					padding: 0.3rem 0.6rem;
					box-sizing: border-box;
					border-radius: 0.1rem;
					.card{
						color:#fff;
						h1{
							font-size: 0.8rem;
							box-sizing: border-box;
							padding-left: 26%;
							margin-top: 0.4rem;
							margin-bottom: 1rem;
							position: relative;
							
						}
						h1::after{
							content: 'VIP';
							font-size: 0.5rem;
							position: absolute;
							right: 30%;
							top:0.6rem;
							font-style:italic;
						}
						
					}
				}
				.no_vip{
					width: 100%;
					position:fixed;
					left: 0;
					bottom: 0;
					z-index: 2;
				}
			}
		
  		}
  		.prompt {
    		padding: 0 0.533rem;
			p {
				font-size: 0.4rem;
				line-height: 0.667rem;
				color: #5a5f5d;
				letter-spacing: 0.027rem;
			}
    		ul{
      			margin-top: 1rem;
      			li{
					color:red;
					font-size: 0.4rem;
					line-height: 0.8rem;
					text-align: center;
        			span{
						position: relative;
						width: 3.6rem;
						display: inline-block;
						text-align: left;
          				&::after{
							content: '';
							width: 6px;
							height: 6px;
							border-radius: 50%;
							border: 1px solid #27b5a7;
							position: absolute;
							left: -12px;
							top:calc(50% - 4px)
						}
						&::before{
							content: '';
							width: 1px;
							height: 0.6rem;
							position: absolute;
							left: -8.5px;
							top:calc(50% + 4px);
							background-color: #27b5a7;
						}
        			}
      			}
      			li:last-child{
					span{
						&::before{
							content: '';
							background-color: transparent;
						}
					}
        
      			}
    		}
  		}

		.van-button {
			width: 90%;
			border-radius: 0.107rem;
			margin: 1.2rem auto 0;
			display: block;
			font-size: 0.56rem;
		}
		
	}
</style>
